package durst.action.account;

import java.io.StringReader;
import java.sql.SQLException;
import java.util.Locale;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.util.UrlBuilder;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import durst.action.CalendarBasicAction;
import durst.data.UserCalendar;
import durst.data.dao.DaoFactory;
import durst.data.dao.impl.UserCalendarDao;

public class CalendarCreateActionBean extends CalendarBasicAction {
	@ValidateNestedProperties({
		@Validate(field="name", required = true, on = "create", minlength = 5, maxlength = 45),
		@Validate(field="shared", required = true, on = "create"),
		@Validate(field="def")
	})
	private UserCalendar cal;
	
	@DefaultHandler
	public Resolution handle() {
		return new ForwardResolution("/account/calendarcreate.jsp");
	}

	@SuppressWarnings("unchecked")
	public Resolution create() throws SQLException {
		UserCalendarDao<UserCalendar, Integer> dao = ((UserCalendarDao<UserCalendar, Integer>) DaoFactory
				.getInstance().createDao(UserCalendar.class));

		if (cal.isDef()) {
			UserCalendar oldDef = dao.getDefaultCalendarForAccount(context.getAccount());
			oldDef.setDef(false);
			dao.update(oldDef);
		}
		
		cal.setOwner(context.getAccount());
		dao.create(cal);

		StringBuilder builder = new StringBuilder();
		builder.append(context.getRequest().getContextPath());

		UrlBuilder url = new UrlBuilder(Locale.US, CalendarActionBean.class, false);
		url.addParameter("cal.id", cal.getId());

		builder.append(url.toString());

		return new StreamingResolution("text/javascript", new StringReader(
				"Lightview.hide(); window.location='" + builder.toString() + "';"));
	}
	
	public UserCalendar getCal() {
		return cal;
	}
	
	public void setCal(UserCalendar cal) {
		this.cal = cal;
	}
}
